package actions.square2Curly;

import utils.ClipBoardUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Square2CurlyInputDialog extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JFormattedTextField formatInput;
    private ICallBack callBack;

    public static void runWithCallBack(ICallBack callBack) {
        Square2CurlyInputDialog dialog = new Square2CurlyInputDialog();
        dialog.callBack = callBack;
        dialog.setTitle("请输入原始数据");
        dialog.pack();
        dialog.setLocation(MouseInfo.getPointerInfo().getLocation());
        dialog.setVisible(true);
    }

    public Square2CurlyInputDialog() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);

        formatInput.setText(ClipBoardUtil.getSysClipboardText());

        buttonOK.addActionListener(e -> onOK());

        buttonCancel.addActionListener(e -> onCancel());

        // call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

        // call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(e -> onCancel(), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
                JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }

    private void onOK() {
        // add your code here
        if (callBack != null) {
            callBack.onConfirm(formatInput.getText());
        }
        dispose();
    }

    private void onCancel() {
        // add your code here if necessary
        dispose();
    }

    public static void main(String[] args) {
        Square2CurlyInputDialog.runWithCallBack(System.out::println);
    }

    public interface ICallBack {
        void onConfirm(String origin);
    }
}
